package roleservicelogic

import (
	"context"
	"database/sql"
	"fmt"

	"smile-sunshine-micorservice/rpc/User/db/crud"
	"smile-sunshine-micorservice/rpc/User/internal/svc"
	"smile-sunshine-micorservice/rpc/User/pb/zipTako.com/SmileSunshine/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	RolesModel crud.RolesModel
}

func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
	return &CreateRoleLogic{
		ctx:        ctx,
		svcCtx:     svcCtx,
		Logger:     logx.WithContext(ctx),
		RolesModel: crud.NewRolesModel(svcCtx.SqlConn, svcCtx.CacheConf),
	}
}

// CreateRole 创建角色
func (l *CreateRoleLogic) CreateRole(in *user.CreateRoleRequest) (*user.CreateRoleResponse, error) {
	l.Logger.Infof("收到创建角色请求，角色名：%s", in.Name)

	// 1. 参数验证
	if err := l.validateCreateRoleRequest(in); err != nil {
		return &user.CreateRoleResponse{
			Success: false,
			Message: err.Error(),
		}, nil
	}

	// 2. 检查角色名是否已存在
	_, err := l.RolesModel.FindOneByName(l.ctx, in.Name)
	if err == nil {
		return &user.CreateRoleResponse{
			Success: false,
			Message: "角色名已存在",
		}, nil
	}

	// 3. 创建角色
	newRole := &crud.Roles{
		Name: in.Name,
		Description: sql.NullString{
			String: in.Description,
			Valid:  in.Description != "",
		},
	}

	result, err := l.RolesModel.Insert(l.ctx, newRole)
	if err != nil {
		l.Logger.Errorf("创建角色失败：%v", err)
		return &user.CreateRoleResponse{
			Success: false,
			Message: "创建角色失败，请稍后重试",
		}, nil
	}

	roleId, err := result.LastInsertId()
	if err != nil {
		l.Logger.Errorf("获取角色ID失败：%v", err)
		return &user.CreateRoleResponse{
			Success: false,
			Message: "创建角色失败，请稍后重试",
		}, nil
	}

	// 4. 返回成功响应
	return &user.CreateRoleResponse{
		Success: true,
		Message: "创建角色成功",
		Role: &user.Role{
			Id:          roleId,
			Name:        in.Name,
			Description: in.Description,
		},
	}, nil
}

// validateCreateRoleRequest 验证创建角色请求参数
func (l *CreateRoleLogic) validateCreateRoleRequest(in *user.CreateRoleRequest) error {
	// 验证角色名
	if len(in.Name) < 2 || len(in.Name) > 50 {
		return fmt.Errorf("角色名长度必须在2-50个字符之间")
	}

	// 验证描述（如果提供）
	if len(in.Description) > 200 {
		return fmt.Errorf("角色描述不能超过200个字符")
	}

	return nil
}
